package com.exercise.ThreadSynchronization.lock;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class LockCounter{
    private int count = 0;
    // 创建一个 ReentrantLock 实例
    private final Lock lock = new ReentrantLock();

    public void increment(){
        lock.lock();
        try{
            count++;
        }finally {
            // 必须在 finally 块中释放锁，确保锁一定会被释放
            lock.unlock();
        }
    }

    /**
     * 读取也加锁是怕一个线程在修改数据，另一个线程又在读取数据，导致读取的数据不是实时的数据
     * @return
     */
    public int getCount(){
        lock.lock();
        try{
            return count;
        }finally {
            lock.unlock();
        }
    }
}
public class LockDemo {
    public static void main(String[] args) throws InterruptedException {
        LockCounter lockCounter = new LockCounter();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                lockCounter.increment();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                lockCounter.increment();
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Final Count: " + lockCounter.getCount());
    }
}
